package day03;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import untils.SessionViewWindow;
import untils.UserBehavior;

import java.time.Duration;

/**
 * 实现会话窗口
 */
public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("D:\\atguigu\\flinkdata\\src\\main\\resources\\UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String s) throws Exception {
                        String[] arr = s.split(",");
                        return new UserBehavior(
                                arr[0],arr[1],arr[2],arr[3],Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                //筛选浏览的窗口
                .filter(r -> r.type.equals("pv"))
                //指定时间戳
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior userBehavior, long l) {
                                        return userBehavior.ts;
                                    }
                                })
                )
                //按照会话id进行分区
                .keyBy(r -> r.userId)
                .process(new fakeSessionWindow(60 * 60 * 1000L))
                .print();

        env.execute();
    }

    /**
     * 会话窗口
     * 参数
     *  会话开始时间
     *  用户不活跃间隙
     */
    public static class fakeSessionWindow extends KeyedProcessFunction<String,UserBehavior, SessionViewWindow>{

        private Long waitTime;//窗口不活跃时间,如果时间内没有新数据,则关闭窗口

        private ValueState<Long> timerTs;//保存定时器的时间戳
        private ValueState<Long> startTs;//保存会话开始时间
        private ValueState<Long> count;//保存会话中数据条数
        private ValueState<String> userid;//保存会话ID

        public fakeSessionWindow(Long waitTime) {
            this.waitTime = waitTime;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            timerTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>("waitTime", Types.LONG));
            startTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>("startTsTime", Types.LONG));
            count = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>("count", Types.LONG));
            userid = getRuntimeContext().getState(
                    new ValueStateDescriptor<String>("userid", Types.STRING));
        }

        @Override
        public void processElement(UserBehavior value, Context ctx, Collector<SessionViewWindow> out) throws Exception {
            if(startTs.value() == null){//当是第一条数据,或者新一个会话
                //保存定时器时间戳,会话开始时间,会话数据条数,会话id
                timerTs.update(value.ts + waitTime - 1L);
                startTs.update(value.ts);
                count.update(1L);
                userid.update(ctx.getCurrentKey());
                //注册定时器
                ctx.timerService().registerEventTimeTimer(value.ts + waitTime - 1L);
            } else {//如果不是第一条数据
                //更新时间戳和用户数据条数
                Long ts = timerTs.value();
                Long counts = count.value();


                timerTs.update(value.ts  + waitTime - 1L);
                count.update(counts + 1L);
                //删除已经存在的定时器,重新注册定时器
                ctx.timerService().deleteEventTimeTimer(ts);
                ctx.timerService().registerEventTimeTimer(value.ts + waitTime - 1L);
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<SessionViewWindow> out) throws Exception {

            out.collect(
                    new SessionViewWindow(
                            userid.value(),
                            count.value(),
                            startTs.value(),
                            timerTs.value() + waitTime
                    ));
            timerTs.clear();
            userid.clear();
            count.clear();
            startTs.clear();

        }
    }
}
